import 'package:chat/common/model/ChatList.dart';
import 'package:chat/common/model/User.dart';
import 'package:chat/common/service/HttpService.dart';
import 'package:chat/common/utils/storage.dart';
import 'package:get/get.dart';

import '../../../common/model/UserMessageModel.dart';

class ChatController extends GetxController {
  ChatController();

  var user = Rxn<UserModel>();
  var chatList = <ChatList>[].obs;
  var loading = true.obs;

  _initData() {
    update(["chat"]);
  }

  Future<void> fetchData() async {
    try {
      final response = await HttpService.to.get("/user-message/list", query: {"userId": user.value?.uid});

      if (response.statusCode == 200 && response.data["code"] == 200) {
        print("数据：${response.data}");

        // 取出 data 部分
        final List<dynamic> list = response.data["data"] ?? [];

        // 转换成模型类
        chatList.value = list.map((e) => ChatList.fromJson(e)).toList();
        print("数据长度：${chatList.length}");
      }
    } catch (e) {
      print("获取聊天列表失败${e}");
    }
  }

  void onTap() {}

  @override
  void onInit() async {
    super.onInit();
    user.value = await Storage().getUser();
    fetchData();
  }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  Future<void> receiveMessage(UserMessageModel userMessage) async {
    try {
      // 1️⃣ 判断消息是否属于当前用户
      final userId = await Storage().getUser();
      if (userId == null || userId.uid != userMessage.receiverId) return;

      // 2️⃣ 查找聊天列表中是否已有该会话
      int index = chatList.indexWhere((chat) => (chat.userId == userMessage.senderId));

      // 3️⃣ 如果已存在该聊天会话 → 更新
      if (index != -1) {
        var oldChat = chatList[index];
        oldChat.lastContent = userMessage.content;
        oldChat.messageType = userMessage.type;

        chatList.removeAt(index);
        chatList.insert(0, oldChat);
        chatList.refresh();
      } else {
        // 新建列表
        final response = await HttpService.to.get("/user/${userMessage.senderId}");

        if (response.statusCode == 200 && response.data["code"] == 200) {
          UserModel user = UserModel.fromJson(response.data["data"]);

          final newChat = ChatList(
            messageId: DateTime.now().millisecondsSinceEpoch,
            userId: user.uid,
            avatar: user.avator,
            name: user.nickname,
            messageType: userMessage.type,
            lastContent: userMessage.content,
          );
          chatList.insert(0, newChat);
          chatList.refresh();
        }
      }

      // 5️⃣ 刷新页面 UI
      update(["chat"]);
    } catch (e) {
      print("❌ receiveMessage 出错: $e");
    }
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }
}
